#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <signal.h>
#include "server.cpp"

void restart(FILE *out, FILE *pidFile, char *pidPath);
void start(FILE *out, FILE *pidFile, char *pidPath);
void stop(FILE *out, FILE *pidFile, char *pidPath);
void usage(char *argv);

int main(int argc, char *argv[])
{
   if(argc != 2)
   {
      usage(argv[0]);
   }

   printf("P2P HTTP Tracker Implementation (c)2012 vorbis\n\n");

   struct stat st;
   char outputFile[1024], pidFile[1024], homeDir[1024], outDir[1024];

   strncpy(homeDir, getenv("HOME"), 1000);
   snprintf(outDir, 1024, "%s/.p2p/", homeDir);
   if(stat(outDir,&st) != 0)
   {
      mode_t processMask = umask(0);
      mkdir(outDir, S_IRWXU | S_IRWXG | S_IRWXO);
      umask(processMask);
   }

   snprintf(outputFile, 1024, "%s/.p2p/tracker.log", homeDir);
   FILE *out = fopen(outputFile, "a");

   snprintf(pidFile, 1024, "%s/.p2p/.pid", homeDir);
   FILE *file = fopen(pidFile, "a+");

   if(!strcmp(argv[1], "start"))
   {
       start(out, file, pidFile);
   }
   else if(!strcmp(argv[1], "stop"))
   {
       stop(out, file, pidFile);
   }
   else if(!strcmp(argv[1], "restart"))
   {
       restart(out, file, pidFile);
   }
   else
   {
       usage(argv[0]);
   }

   return 0;
}

void restart(FILE *out, FILE *pidFile, char *pidPath)
{
   stop(out, pidFile, pidPath);
   start(out, pidFile, pidPath);
}

void start(FILE *out, FILE *pidFile, char *pidPath)
{
   char pidChar[1024];
   char *ret = fgets(pidChar, 1023, pidFile);

   if(ret != NULL)
   {
      printf("Already running! PID: %s", pidChar);
      printf("If this is in error, please delete %s\n", pidPath);
      fclose(pidFile);
      fclose(out);
      exit(0);
   }

   fprintf(out, "STARTING: server\n");

   if (fork() != 0)
   {
      exit(0);
   }

   int pid = fork();
   if(pid == 0)
   {
      tracker(out);
      fclose(pidFile);
      fclose(out);
      exit(0);
   }
   else
   {
      fprintf(out, "PID: %d\n", pid);

      fclose(pidFile);
      pidFile = fopen(pidPath, "w");
      fprintf(pidFile, "%d\n", pid);
      fclose(pidFile);
      fclose(out);
      exit(0);
   }
}

void stop(FILE *out, FILE *pidFile, char *pidPath)
{
   char pidChar[1024], command[1024];
   fprintf(out, "STOPPING: server\n");
   fclose(out);
   fgets(pidChar, 1023, pidFile);

   if(strcmp(pidChar, "") != 0)
   {
      snprintf(command, 1024, "kill -9 %s", pidChar);
      system(command);
//      kill(cast(pidChar),SIGKILL);
      fclose(pidFile);

      pidFile = fopen(pidPath, "w");
      fclose(pidFile);
   }
   else
   {
      fclose(pidFile);
   }
}

void usage(char *argv)
{
   printf("Usage: %s {start|stop|restart}\n", argv);
   exit(0);
}

